
package com.express.util;

import com.github.pagehelper.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件帮助类
 */
public class IOUtil {
    public static final Logger logger = LoggerFactory.getLogger(com.express.util.IOUtil.class);
    private static String FILE_PATH = (new SimpleDateFormat("yyyyMM")).format(new Date())+ "/"+ (new SimpleDateFormat("dd")).format(new Date());
    public static final String BASE_PATH = "/var/www/exp/web/static/upload/";
    public static final String PDF_PATH;



    public IOUtil() {
    }

    public static String inputStreamToString(InputStream inputStream, String encoding) throws IOException {
        if (StringUtil.isEmpty(encoding)) {
            encoding = "utf-8";
        }

        return IOUtils.toString(inputStream, encoding);
    }

    public static InputStream toInputStream(String inputStr, String encoding) throws IOException {
        if (StringUtil.isEmpty(inputStr)) {
            return null;
        } else {
            if (StringUtil.isEmpty(encoding)) {
                encoding = "utf-8";
            }

            return IOUtils.toInputStream(inputStr, encoding);
        }
    }

    public static String urlEncode(String source, String encode) {
        String result = source;

        try {
            result = URLEncoder.encode(source, encode);
        } catch (UnsupportedEncodingException var4) {
            var4.printStackTrace();
        }

        return result;
    }

    public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        return IOUtils.toByteArray(inputStream);
    }

    public static String downFile(HttpServletRequest request, HttpServletResponse response, String filePath, String filename, String type) {
        try {
            if (StringUtil.isEmpty(filePath) && StringUtil.isEmpty(filename) && StringUtil.isEmpty(type)) {
                logger.info("~~~~~~~~~~~~文件下载参数为空~~~~~~~~");
                return "";
            }

            File file = new File(filePath);
            if (file.exists()) {
                logger.info("~~~~~~~~~~~~进入文件下载~~~~~~~~");
                FileInputStream fis = new FileInputStream(file);
                String header = request.getHeader("User-Agent").toUpperCase();
                String newfileName = "";
                if (!header.contains("MSIE") && !header.contains("TRIDENT") && !header.contains("EDGE") && !header.contains("LIKE GECKO")) {
                    newfileName = new String(filename.getBytes("utf-8"), "ISO8859-1");
                } else {
                    newfileName = URLEncoder.encode(filename, "utf-8");
                    newfileName = newfileName.replace("+", "%20");
                }

                if (type.equals("C")) {
                    filename = newfileName;
                }

                response.reset();
                response.setContentType("application/force-download;application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "ISO8859-1"));
                ServletOutputStream out = response.getOutputStream();
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;

                try {
                    bis = new BufferedInputStream(fis);
                    bos = new BufferedOutputStream(out);
                    byte[] buff = new byte[2048];

                    int bytesRead;
                    while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                        bos.write(buff, 0, bytesRead);
                    }
                } catch (IOException var18) {
                    throw var18;
                } finally {
                    if (bis != null) {
                        bis.close();
                    }

                    if (bos != null) {
                        bos.close();
                    }

                }
            }
        } catch (Exception var20) {
            var20.printStackTrace();
        }

        return null;
    }

    public static String getFileParentPath(){
        return BASE_PATH + FILE_PATH +"/";
    }

    public static String saveFile(MultipartFile file, String filename, String path, int sum) {
        if (!file.isEmpty()) {
            try {
                String temp = (new SimpleDateFormat("yyyyMM")).format(new Date())+ "/"+ (new SimpleDateFormat("dd")).format(new Date());
                String filedir = path + temp;
                File pathfile = new File(filedir+"/");
                if(FILE_PATH != temp){
                    FILE_PATH = temp;
                }
                if (!pathfile.exists()) {
                    pathfile.mkdirs();
                }
//                int no = (int)((double)sum + Math.random() * 100.0D);
                String no = RandomNumber.getOrderNo("");
                String newFileName = no + filename.substring(filename.lastIndexOf("."));
                File writeFile = new File(filedir+"/"+ newFileName.replace("-", ""));
                file.transferTo(writeFile);
                return newFileName;
            } catch (Exception var7) {
                var7.printStackTrace();
            }
        }
        return "";
    }
    /**
     * 重命名文件
     * @param fileName
     * @return
     */
    public static void renameFile(String filePath, String fileName,String newFileName) {
        try {
            String oldFileName = filePath+fileName;
            File oldFile = new File(oldFileName);
            String sufix = fileName.substring(fileName.lastIndexOf("."));
            //创建新名字的抽象文件
//            File newFile = new File(oldFile.getParent()+File.separator+newFileName+sufix);
            //
            copy(oldFileName,oldFile.getParent()+File.separator+"/images/"+newFileName+sufix);
//            if (oldFile.exists() && oldFile.isFile()) {
//                if(!newFile.exists()){
//                    newFile.createNewFile();
//                }
//                oldFile.renameTo(newFile);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void copy(String srcPath,String destPath) {
        //1，创建源
        File src=new File(srcPath);
        File dest=new File(destPath);//这个文件不存在，（自动创建）
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        // 2，选择流
        InputStream is=null;
        OutputStream os=null;
        try {
            is=new FileInputStream(src);
            os=new FileOutputStream(dest);
            //3,操作（写出）
            //3，操作（分段读取）
            byte[] flush=new byte[1024];//中间的缓冲容器
            int len=-1;//接收长度初始化值
            while((len=is.read(flush))!=-1) {//is.read(car)返回的是一个int值，当前读取字节的长度
                os.write(flush, 0, len);
            }
            os.flush();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4，释放资源（分别关闭）（先打开的后关闭）
            try {
                if(null!=os) {
                    os.close();
                }
            }catch(IOException e) {

            }
            try {
                if(null!=is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeTxt(String path, String conent) {
        BufferedWriter out = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, true)));
            out.write(new String(conent.getBytes(),"utf-8") + "\r\n");
        } catch (Exception var12) {
            var12.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException var11) {
                var11.printStackTrace();
            }

        }

    }

    public static boolean delFile(String path, String filename) {
        File file = new File( path + filename);
        if (file.exists() && file.isFile()) {
            file.delete();
            return true;
        } else {
            return false;
        }
    }

    public static void zipFiles(List<File> srcFiles, File zipFile) {
        if (!zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }

        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException var9) {
                var9.printStackTrace();
            }
        }

        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        FileInputStream fileInputStream = null;

        try {
            fileOutputStream = new FileOutputStream(zipFile);
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            ZipEntry zipEntry = null;

            for(int i = 0; i < srcFiles.size(); ++i) {
                fileInputStream = new FileInputStream((File)srcFiles.get(i));
                zipEntry = new ZipEntry(((File)srcFiles.get(i)).getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buffer = new byte[1024];

                int len;
                while((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }

            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException var10) {
            var10.printStackTrace();
        }

    }
    // 将数字转换为String类型
    private static void numberToString(Function<Number, String> function) {
        String apply = function.apply(12);
        System.out.println("转换结果:"+apply);
    }
    // 静态方法
    private static void method_andThen(Function<Integer, Integer> f1,Function<Integer, Integer> f2) {
        Integer apply = f1.andThen(f2).apply(2);
//        System.out.println(f1.apply());
        System.out.println(apply);
    }
    private static void method_compose(Function<Integer, Integer> f1, Function<Integer, Integer> f2) {
        Integer apply = f1.compose(f2).apply(2);
        System.out.println(apply);
    }

    public static boolean isExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    static {
        PDF_PATH = "D:/uploadFile/" + FILE_PATH.substring(0, 6) + "/" + FILE_PATH.substring(6, FILE_PATH.length()) + "/";
    }

    public static void main(String[] args) throws Exception {
//        IOUtil.delFile(IOUtil.BASE_PATH,"微信图片_20201221101016.jpg");
        System.out.println("69412281033921".length());
        numberToString((s) -> String.valueOf(s));
        method_andThen(s -> s + 1, s -> s = s * 2);//6
        method_compose(s -> s + 1, s -> s = s * s);//5

    }
}
